import Cookies from 'js-cookie'

// 存储方式配置：'cookie' 或 'localStorage' 或 'sessionStorage'
let STORAGE_TYPE = 'localStorage' // 默认使用localStorage
const TokenKey = 'award_review_template_token'

// 根据配置获取对应的存储工具
const getStorage = () => {
    switch(STORAGE_TYPE) {
        case 'cookie':
            return {
                get: (key) => Cookies.get(key),
                set: (key, value) => Cookies.set(key, value),
                remove: (key) => Cookies.remove(key)
            }
        case 'sessionStorage':
            return {
                get: (key) => sessionStorage.getItem(key),
                set: (key, value) => sessionStorage.setItem(key, value),
                remove: (key) => sessionStorage.removeItem(key)
            }
        default: // localStorage
            return {
                get: (key) => localStorage.getItem(key),
                set: (key, value) => localStorage.setItem(key, value),
                remove: (key) => localStorage.removeItem(key)
            }
    }
}

// 统一的存储工具实例
const storage = getStorage()

// 对外暴露的接口保持不变
export function getToken() {
    return storage.get(TokenKey)
}

export function setToken(token) {
    return storage.set(TokenKey, token)
}

export function removeToken() {
    return storage.remove(TokenKey)
}

// 提供动态切换存储方式的方法（可选）
export function setStorageType(type) {
    if (['cookie', 'localStorage', 'sessionStorage'].includes(type)) {
        // 切换存储类型时，将现有Token迁移到新的存储方式
        const token = getToken()
        removeToken()

        // 更新存储类型并重新初始化存储工具
        STORAGE_TYPE = type
        Object.assign(storage, getStorage())

        // 迁移Token
        if (token) {
            setToken(token)
        }
        return true
    }
    return false
}
